package main

import (
	"embed"
	"fmt"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"os"
	"path/filepath"
	"time"
)

//go:embed database/sql.db
var dbFile embed.FS

type Config struct {
	Id         uint   `gorm:"column:id" form:"id" json:"id"`
	HtmlPrefix string `gorm:"column:html_prefix" form:"html_prefix" json:"html_prefix"`
	DocPrefix  string `gorm:"column:doc_prefix" form:"doc_prefix" json:"doc_prefix"`
}

type History struct {
	Id        uint      `gorm:"column:id" form:"id" json:"id"`
	RmDoc     string    `gorm:"column:rm_doc;unique" form:"rm_doc" json:"rm_doc"`
	CreatedAt time.Time `gorm:"column:created_at;unique" form:"created_at" json:"created_at"`
}

// 只加载一次
var (
	Gorm *gorm.DB
)

func init() {
	// 目标数据库文件路径
	dbDir := "database" // 数据库文件存放目录
	dbPath := filepath.Join(dbDir, "sql.db")

	// 检查目标目录是否存在，如果不存在则创建
	if _, err := os.Stat(dbDir); os.IsNotExist(err) {
		if err := os.MkdirAll(dbDir, 0755); err != nil {
			panic(fmt.Sprintf("Failed to create database directory: %v", err))
		}
	}
	// 使用目标路径初始化 SQLite 数据库
	var err error
	Gorm, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		panic(fmt.Sprintf("Failed to open database: %v", err))
	}

	// 自动迁移表结构
	Gorm.AutoMigrate(&Config{})
	Gorm.AutoMigrate(&History{})

	// 初始化配置
	cfg := Config{}
	result := Gorm.First(&cfg)
	if result.RowsAffected == 0 {
		Gorm.Create(&Config{
			Id:         1,
			HtmlPrefix: "/home/html",
			DocPrefix:  "/home/html/diy/app/static/file",
		})
	}
}

type Query struct {
	Orm *gorm.DB
}

func NewQuery() *Query {
	return &Query{
		Orm: Gorm,
	}
}

func (q *Query) SaveConfig(html_prefix string, doc_prefix string) {
	config := Config{}
	Gorm.First(&config)
	config.HtmlPrefix = html_prefix
	config.DocPrefix = doc_prefix
	Gorm.Save(&config)
}

func (q *Query) GetConfig() (html_prefix string, doc_prefix string) {
	config := Config{}
	Gorm.First(&config)
	return config.HtmlPrefix, config.DocPrefix
}
